/**
 *  This file is part of MunchLevel.
 *
 *  MunchLevel is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  MunchLevel is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with MunchLevel.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.munchlevel.util;

import java.util.ArrayList;
import java.util.Collection;

/**
 * @author Ganymede
 * 
 */
public class LimitedList<E> extends ArrayList<E> {

	private static final long serialVersionUID = 80268301724749682L;

	private int capacity;

	/**
	 * 
	 */
	public LimitedList(int capacity) {
		super(capacity);
		this.capacity = capacity;
	}

	public boolean add(E object) {
		_clearListLastItem();
		return super.add(object);
	}

	public void add(int index, E object) {
		_clearListLastItem();
		super.add(index, object);
	};

	public int getCapacity() {
		return capacity;
	}

	public void setCapacity(int capacity) {
		this.capacity = capacity;

		_clearListLastItemPost();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.util.ArrayList#addAll(java.util.Collection)
	 */
	@Override
	public boolean addAll(Collection<? extends E> collection) {
		boolean result = super.addAll(collection);
		_clearListLastItemPost();
		return result;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.util.ArrayList#addAll(int, java.util.Collection)
	 */
	@Override
	public boolean addAll(int location, Collection<? extends E> collection) {
		boolean result = super.addAll(location, collection);
		_clearListLastItemPost();
		return result;
	}

	private void _clearListLastItem() {
		while (size() >= capacity)
			remove(0);
	}

	private void _clearListLastItemPost() {
		while (size() > capacity)
			remove(0);
	}

}
